package com.hmall.order.mq;

import com.hmall.common.clients.ItemClient;
import com.hmall.common.utils.UserHolder;
import com.hmall.order.pojo.Order;
import com.hmall.order.pojo.OrderDetail;
import com.hmall.order.service.impl.OrderDetailService;
import com.hmall.order.service.impl.OrderService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Map;
import java.util.Objects;

import static com.hmall.common.constants.MqConstants.HMALL_DL_QUEUE;

@Slf4j
@Component
public class RabbitMQListener {
    @Autowired
    private ItemClient itemClient;
    @Autowired
    private OrderService orderService;
    @Autowired
    private OrderDetailService orderDetailService;

    /**
     * 死信队列消费者
     */
    @Transactional(rollbackFor = Exception.class)
    @RabbitListener(queues = {HMALL_DL_QUEUE})
    public void dlQueueConsumer(Map<String, Object> message) {
        log.info("死信队列消费者 消费消息：{}", message);
        Long userId = (Long) message.get("userId");
        Long orderId = (Long) message.get("orderId");
        UserHolder.setUser(userId);
        //1、查询订单
        Order order = orderService.getById(orderId);
        //2、状态是非未支付，无需任何操作
        if(Objects.isNull(order) || order.getStatus()!=1){
            return;
        }
        //3、状态是未支付，取消订单、回加库存
        orderService.lambdaUpdate().set(Order::getStatus,5).eq(Order::getId,orderId).update();
        List<OrderDetail> orderDetails = orderDetailService.lambdaQuery().eq(OrderDetail::getOrderId, orderId).list();
        for(OrderDetail orderDetail:orderDetails){
            itemClient.updateStockById(orderDetail.getItemId(),"add",orderDetail.getNum());
        }
        UserHolder.removeUser();
    }
}
